package com.flyco.modules.jddj.controller;

import com.flyco.common.api.vo.Result;
import com.flyco.common.util.DateUtils;
import com.flyco.modules.jddj.handle.IJddjOrderHandle;
import com.flyco.modules.jddj.vo.JddjResult;
import com.flyco.modules.jddj.vo.JddjTokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

@Slf4j
@Api(tags="京东到家")
@RestController
@RequestMapping("/f/c/jddj")
public class JddjOrderController {

    @Autowired
    private IJddjOrderHandle jddjOrderHandle;

    /**
     * 同步京东订单
     *
     * @return
     */
    @ApiOperation(value="同步京东订单")
    @GetMapping(value = "/syncJddjOrder")
    public Result<?> syncJddjOrder() {
        try {
            String jddjOrder = jddjOrderHandle.getJddjOrder();
            return Result.ok(jddjOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("同步成功！");
    }

    /**
     *   获取京东到家Token，保存到文件中
     *
     * @return
     */
    @PostMapping(value = "/callBack")
    public JddjResult callBack(JddjTokenVO vo) {
        String filePath = "jddj-token-" + DateUtils.date2Str(DateUtils.yyyymmddhhmmss.get()) + ".txt";
        log.info("filePath:" + filePath);
        StringBuilder content = new StringBuilder();
        content.append("token：" + vo.getToken());
        content.append(System.getProperty("line.separator"));
        content.append("expires_in：" + vo.getExpires_in());
        content.append(System.getProperty("line.separator"));
        content.append("time：" + vo.getTime());
        content.append(System.getProperty("line.separator"));
        content.append("uid：" + vo.getUid());
        content.append(System.getProperty("line.separator"));
        content.append("user_nick：" + vo.getUser_nick());
        content.append(System.getProperty("line.separator"));
        content.append("venderId：" + vo.getVenderId());
        saveAsFileWriter(filePath, content.toString());
        return new JddjResult();
    }


    private static void saveAsFileWriter(String filePath, String content) {
        FileWriter fwriter = null;
        try {
            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
            fwriter = new FileWriter(filePath, true);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.flush();
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
